import { useEffect, useRef, useState } from 'react';
import { useToggle } from 'ahooks';
import { Button, Drawer, Modal, Input } from 'antd';
import { DeleteFilled } from '@ant-design/icons';
import {
  HashRouter as Router,
  Route,
  Routes,
  useNavigate,
} from 'react-router-dom';
import DetailCmp from './components/detail';
import DiyPage from '../pages/index';
import './App.css';

type FileResp = {
  head: string[];
  data: {
    [key: string]: Array<Array<string>>;
  };
  json: any;
};

const EntryPage = () => {
  const [loading, { setLeft, setRight }] = useToggle(false);
  const [openTable, setOpenTable] = useState(false);
  const [data, setData] = useState<{
    [key: string]: Array<Array<string>>;
  }>({});
  const [heads, setHeads] = useState<string[]>([]);
  const [filePath, setFilePath] = useState<string>();
  const ipt = useRef<any>(null);
  const bookRef = useRef<any>(null);
  const navigater = useNavigate();
  const clearn = () => {
    setFilePath(undefined);
    setData({});
    setHeads([]);
    setOpenTable(false);
  };

  const jump = () => {
    navigater('/diy');
  };

  useEffect(() => {
    window.electron.ipcRenderer.on('openFile', (result) => {
      const { book, filePath: path } = result as {
        filePath: string;
        book: unknown;
      };
      bookRef.current = book;
      setFilePath(path);
    });

    window.electron.ipcRenderer.on('decodeFile', (resp) => {
      const { head, data: rp } = resp as FileResp;
      setData(rp);
      setHeads(head);
      setOpenTable(true);
      setLeft();
    });

    window.electron.ipcRenderer.on('onerror', (error) => {
      const ed = JSON.parse(error as string) as {
        type: number;
        message: string;
        info?: any;
      };
      if (![1, 4, 5].includes(ed.type)) {
        Modal.error({
          title: '出错了',
          content: ed.message,
        });
      }
    });

    window.electron.ipcRenderer.on('export', (path) => {
      Modal.success({
        content: `导出成功, 附件位置在${path}`,
      });
    });
  }, [setLeft]);

  return (
    <div className="body">
      <div className="Hello">
        {!filePath && (
          <>
            <h1>添加文件</h1>
            <button
              className="button"
              type="button"
              onClick={() => {
                window.electron.ipcRenderer.sendMessage('openFile');
              }}
            >
              打开
            </button>
            <button type="button" className="link" onClick={jump}>
              自定义解析
            </button>
          </>
        )}
        {filePath && (
          <>
            <h3>
              {filePath}
              <Button
                type="text"
                danger
                icon={<DeleteFilled />}
                onClick={clearn}
              />
            </h3>
            <div style={{ padding: 12 }}>
              <Input ref={ipt} placeholder="请输入" />
              <p style={{ padding: 6 }}>输入解析关键字，例：品牌、日期、规格</p>
            </div>
            <div>
              <button
                className="button"
                type="button"
                style={{ marginRight: 12 }}
                onClick={() => {
                  const keyword = ipt.current.input.value;
                  setRight();
                  if (keyword) {
                    window.electron.ipcRenderer.sendMessage('decodeFile', {
                      book: bookRef.current,
                      keyword,
                    });
                  } else {
                    Modal.error({
                      title: '出错了',
                      content: '请输入你想解析的关键词',
                    });
                    setLeft();
                  }
                }}
              >
                开始解析
              </button>
              <button
                className="button"
                type="button"
                onClick={() => {
                  window.electron.ipcRenderer.sendMessage('openFile');
                }}
              >
                重新选择
              </button>
            </div>
          </>
        )}
      </div>
      {loading && (
        <div className="loading">
          <p>解析中...</p>
          <Button type="default" onClick={setLeft}>
            取消
          </Button>
        </div>
      )}

      <Drawer
        title="解析详情"
        width="100%"
        open={openTable}
        onClose={() => setOpenTable(false)}
      >
        <DetailCmp data={data} heads={heads} />
      </Drawer>
    </div>
  );
};

export default () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<EntryPage />} />
        <Route path="/diy" element={<DiyPage />} />
      </Routes>
    </Router>
  );
};
